import { createClient } from "redis";
import { emailType } from "../common";
import { getUserUsedCount } from "./db";
console.log("开始连接 Redis");

export const client = createClient({
  url: "rediss://default:AS4GAAIjcDE0MWM2NzQ2ZjI5ZDk0M2UyODNhZDg0ZDczNzRhZWFkZXAxMA@classic-cheetah-11782.upstash.io:6379",
});

client.on("connect", () => {
  console.log("Redis连接成功");
});

client.on("error", (err) => {
  console.error("Redis Error:", err);
});
// 设置 OTP，过期时间 10 分钟
export async function setOtp(
  email: string,
  otp: string,
  type: emailType,
  userIp: string
) {
  try {
    const key = `otp:${email}-${type}`;
    await client.set(key, otp, { EX: 600 }); // 设置过期时间为 600 秒（10 分钟）
    console.log(userIp + `OTP 已存储: ${otp} (邮箱: ${email}) (类型: ${type})`);
  } catch (error) {
    console.error(userIp + "设置 OTP 失败:", error);
  }
}
// 验证 OTP（匹配成功后删除）
export async function verifyOtp(email: string, otp: string, type: emailType) {
  try {
    const key = `otp:${email}-${type}`;
    const storedOtp = await client.get(key);

    if (storedOtp && storedOtp === otp) {
      await client.del(key); // 匹配成功后删除 OTP
      console.log(`OTP 验证成功 (邮箱: ${email})`);
      return true;
    } else {
      console.log(`OTP 验证失败 (邮箱: ${email})`);
      return false;
    }
  } catch (error) {
    console.error("验证 OTP 失败:", error);
    return false;
  }
}
// 关闭 Redis 连接
export async function closeConnection() {
  await client.quit();
  console.log("Redis 连接已关闭");
}
//设置用户信息
export async function setUser(
  email: string,
  accountId: string,
  sessionId: string
) {
  try {
    const key = `sessionsss:${sessionId}`;
    if (await client.exists(key)) {
      console.log(
        `用户 已存在: ${sessionId} (邮箱: ${email}) (账号: ${accountId})`
      );
      return true;
    }
    const val = JSON.stringify({ email, accountId });
    await client.set(key, val, { EX: 86400 }); // 设置过期时间为 一天
    console.log(
      `用户 已存储: ${sessionId} (邮箱: ${email}) (账号: ${accountId})`
    );
    return true;
  } catch (error) {
    console.error("设置用户信息失败:", error);
    return false;
  }
}
//设置用户已经使用存储数量
export async function setUserCount(accountId: string, count: number) {
  try {
    const key = `used:${accountId}`;
    const val = count;
    await client.set(key, val); // 设置永不过期
    return true;
  } catch (error) {
    console.error("设置用户信息失败:", error);
    return false;
  }
}
//获取用户当前存储量
export async function getUserCount(accountId: string) {
  try {
    const key = `used:${accountId}`;
    const ifExists = await client.exists(key);
    if (ifExists) {
      const val = await client.get(key);
      return val;
    } else {
      const val = await getUserUsedCount(accountId);
      await setUserCount(accountId, val);
      return val;
    }
  } catch (error) {
    console.log("查无用户:", error);
    return -1;
  }
}
//获取用户信息
export async function getUserMes(sessionId: string) {
  try {
    const key = `sessionsss:${sessionId}`;
    const user = await client.get(key);
    return JSON.parse(user);
  } catch (error) {
    console.log("查无用户:", error);
    return null;
  }
}

//删除用户信息
export async function delUser(sessionId: string) {
  try {
    const key = `session:${sessionId}`;
    const exists = await client.exists(key);

    if (exists) {
      await client.del(key);
      console.log("\n" + `用户已删除: ${sessionId}`);
    } else {
      console.log("\n" + `用户不存在: ${sessionId}`);
    }

    return true;
  } catch (error) {
    console.error("删除用户信息失败:", error);
    return false;
  }
}

client.connect();
